import os
from flask import Flask, make_response
from flask import request
import urllib.parse
from JCI_APIs import *
import json

app = Flask(__name__)

global re_data
re_data = {
    'code': 4000,
    'msg': 'failed',
    'data': []
}

# app.config['SERVER_NAME'] = 'jciwebsite-apis.pasp.cn:80'


# 解决跨域数据通信
@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin'] = '*'
    environ.headers['Access-Control-Allow-Method'] = '*'
    environ.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return environ


@app.route('/')
def default():
    return 'Access Denied!!!'


def response_data():
    global re_data
    return json.dumps(re_data, ensure_ascii=False)


@app.route('/get_jci_column_data', methods=['GET'])
def get_jci_column_data():
    global re_data
    re_data['code'] = 2000
    re_data['msg'] = 'success'
    re_data['data'] = get_jci_column()
    return response_data()


@app.route('/get_jci_news_list_data', methods=['GET'])
def get_jci_news_list_data():
    global re_data
    re_data['data'] = []
    try:
        cid = int(request.args.get("cid"))
        if isinstance(cid, int) and cid < get_jci_column_len():
            re_data['code'] = 2000
            re_data['msg'] = 'success'
            re_data['data'] = get_jci_news(cid)
        else:
            re_data['code'] = 4001
            re_data['msg'] = '参数不在约定范围内，请参考get_jci_column_data接口cid参数'
    except ValueError:
        re_data['code'] = 4002
        re_data['msg'] = '参数异常！'
    return response_data()


@app.route('/get_jci_news_content_data', methods=['GET'])
def get_jci_news_content_data():
    global re_data
    re_data['data'] = []
    try:
        cid = int(request.args.get("news_col"))
        nid = int(request.args.get("news_id"))
        if isinstance(cid, int) and isinstance(nid, int):
            re_data['code'] = 2000
            re_data['msg'] = 'success'
            re_data['data'] = get_jci_contents(cid, nid)
        else:
            re_data['code'] = 4001
            re_data['msg'] = '参数非法！'
    except ValueError:
        re_data['code'] = 4002
        re_data['msg'] = '参数异常！'
    return response_data()


@app.route('/get_jci_web_content_data', methods=['GET'])
def get_jci_web_content_data():
    global re_data
    re_data['data'] = []
    try:
        url = urllib.parse.unquote(request.args.get("url"))
        if url != "":
            re_data['code'] = 2000
            re_data['msg'] = 'success'
            re_data['data'] = get_jci_web_content(url)
        else:
            re_data['code'] = 4001
            re_data['msg'] = '参数非法！'
    except ValueError:
        re_data['code'] = 4002
        re_data['msg'] = '参数异常！'
    return response_data()


@app.route('/<path>')
def read_file(path):
    base_dir = os.path.dirname(__file__)
    resp = make_response(open(os.path.join(base_dir, path),encoding='utf-8').read())
    resp.headers["Content-type"] = "text/plan;charset=UTF-8"
    return resp


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=810)
